package fun.easycode.webterminal.common.config;

import cn.hutool.core.util.IdUtil;
import fun.easycode.webterminal.common.util.TraceIdUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jboss.logging.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.thymeleaf.util.StringUtils;

public class RequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader("traceId");
        if(StringUtils.isEmpty(traceId)){
            traceId = IdUtil.getSnowflakeNextIdStr();
        }
        MDC.put("traceId", traceId);
        TraceIdUtil.setTraceId(traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove("traceId");
        TraceIdUtil.removeTraceId();
    }
}